package com.relax.feture;

import java.io.*;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

/**
 * 多线程计算数据之和
 */
public class FutureSum {

    private static String[] lines;

    public FutureSum(String filePath) throws IOException {
        File file = new File(filePath);
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
        String line = null;
        int i = 0;
        while ((line = bufferedReader.readLine()) != null) {
            i++;
        }
        this.lines = new String[i];
        System.out.println(i);

    }

    public void readFile(String filePath) throws Exception {
        File file = new File(filePath);
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
        String line = null;
        int i = 0;
        while ((line = bufferedReader.readLine()) != null) {
            lines[i] = line;
            i++;
        }
    }

    public static void main(String[] args) throws Exception {
        FutureSum f = new FutureSum("E:\\dubbo\\Thread\\src\\main\\resources\\sum.txt");
        f.readFile("E:\\dubbo\\Thread\\src\\main\\resources\\sum.txt");
        int sumAll = 0;
        /**
         *多线程计算
         */
        for (final String line : f.lines) {


            Callable<Integer> callable = new Callable<Integer>() {
                public Integer call() throws Exception {
                    int sum = 0;
                    String[] words = line.split(",");
                    for (String word : words) {
                        sum += Integer.parseInt(word);
                    }
                    return sum;
                }
            };
            FutureTask<Integer> task = new FutureTask<Integer>(callable);
            new Thread(task).start();
            Integer sum = task.get();
            System.out.println(Thread.currentThread() + "线程执行的结果是:" + sum);
            sumAll += sum;

        }

//        while (Thread.activeCount() > 0) {
//        }

        System.out.println("最后的结果是:" + sumAll);

    }


}
